//
//  BuyPowerController.swift
//  SCA
//
//  Created by tjun on 2025/9/16.
//

import UIKit
import SnapKit



class BuyPowerSelectCoinView: UIView {
    
    let nameLabel = UILabel(font: UIFontMediumMake(16), textColor: .white)

    override init(frame: CGRect) {
        super.init(frame: frame)
  
        nameLabel.addTo(self)
        nameLabel.snp.makeConstraints { make in
            make.left.equalTo(AppStyle.margin.left)
            make.centerY.equalToSuperview()
        }
        
        let selectButton = UIButton(image: UIImage(named: "selectCoinArrow"))
        selectButton.addTo(self)
        selectButton.isUserInteractionEnabled = false
        selectButton.snp.makeConstraints { make in
            make.right.centerY.equalToSuperview()
            make.width.height.equalTo(35)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

 

class BuyPowerController: BaseController {


   let model: PurchasePowerListModel
    
    private var scrollView: UIScrollView!
    private var contentView: UIView!
    private let codeTextField = LabeledTextField(tip: "只限标准熔铸 $2088".localizedString)
    private var lastView: UIView!
    private var infoModel: BuyPowerModel?
    
    private var paymentOption: BuyPowerPaymentOption?
    
    private let buyButton = MainButton(type: .system, title: "熔铸".localizedString, font: UIFontMake(16), textColor: .white)
    private let buyPowerSelectCoinView = BuyPowerSelectCoinView()
    private let generalTypeView = ComputingPowerTypeView()
    private let standardTypeView = ComputingPowerTypeView()
    private let computingPowerView = ComputingPowerView()
    private let buyComputingPowerAmountView = BuyComputingPowerAmountView()
    
    private let priceCodeView = UIView()
    
    init(model: PurchasePowerListModel) {
        self.model = model
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationBar.backgroundColor = .clear
        
        scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: view.width, height: screenHeight)).addTo(view)
        scrollView.keyboardDismissMode = .onDrag
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.alwaysBounceVertical = true
        scrollView.contentInsetAdjustmentBehavior = .never
        
        let contentSize = CGSize(width: scrollView.width, height: scrollView.height)
        scrollView.contentSize = contentSize
        
        contentView = UIView().addTo(scrollView)
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.size.equalTo(contentSize)
        }
        
        let headerView = UIView(frame: CGRectMake(0, 0, screenWidth, 200)).addTo(contentView)
        let backgroundImageView = UIImageView().addTo(headerView)
        backgroundImageView.image = UIImage(fileName: "powerDetail_bg")
        backgroundImageView.contentMode = .scaleAspectFill
        backgroundImageView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
        }
        
        let coinImageView = UIImageView().addTo(headerView)
        coinImageView.setImage(url: model.poolIcon)
        coinImageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(navBarHeight)
            make.width.height.equalTo(90)
        }
        
        let nameLabel = UILabel(text: model.title, font: UIFontSemiboldMake(18), textColor: .white).addTo(headerView)
        nameLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(coinImageView.snp.bottom).offset(8)
        }
  
        let projectBriefLabel = UILabel(textColor: .white).addTo(headerView)
        
        
        projectBriefLabel.attributedText = String(format: "项目简介\n%@".localizedString, model.description).titleMargin(3, font: UIFontMake(14))
        projectBriefLabel.numberOfLines = 0
        projectBriefLabel.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(AppStyle.margin.left)
            make.top.equalTo(nameLabel.snp.bottom).offset(25)
        }
        
        let outputIncomeView = buildOutputIncomeView().addTo(contentView)
        outputIncomeView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(AppMargin.left)
            make.top.equalTo(projectBriefLabel.snp.bottom).offset(10)
            make.height.equalTo(40)
        }
        
        buyPowerSelectCoinView.addTo(contentView)
        buyPowerSelectCoinView.addTapGesturesWithTarget(target: self, action: #selector(buyPowerSelectCoinViewTapped(_ :)))
        buyPowerSelectCoinView.nameLabel.text = "选择".localizedString
        buyPowerSelectCoinView.layer.cornerRadius = 10
        buyPowerSelectCoinView.layer.masksToBounds = true
        buyPowerSelectCoinView.layer.borderWidth = 0.7
        buyPowerSelectCoinView.layer.borderColor = UIColorMake(0xD2D2D2).cgColor
        buyPowerSelectCoinView.snp.makeConstraints { make in
            make.top.equalTo(outputIncomeView.snp.bottom).offset(10)
            make.left.right.equalToSuperview().inset(AppStyle.margin.left)
            make.height.equalTo(48)
        }
        
        buildPriceCodeView()
        priceCodeView.addTo(contentView)
        priceCodeView.alpha = 0
        priceCodeView.snp.makeConstraints { make in
            make.top.equalTo(buyPowerSelectCoinView.snp.bottom).offset(10)
            make.left.right.equalTo(projectBriefLabel)
        }

        computingPowerView.addTo(contentView)
        computingPowerView.computingPowerValue = 0.0
        computingPowerView.vitalityValue = 0.0
        computingPowerView.layer.cornerRadius = 10
        computingPowerView.layer.masksToBounds = true
        computingPowerView.layer.borderWidth = 0.7
        computingPowerView.layer.borderColor = UIColorMake(0xD2D2D2).cgColor
        computingPowerView.snp.makeConstraints { make in
            make.left.right.equalTo(buyPowerSelectCoinView)
            make.top.equalTo(buyPowerSelectCoinView.snp.bottom).offset(10)
        }
        
        computingPowerView.onInfoButtonTapped = {[weak self] in
            guard let weakSelf = self else { return }
            
            MessageAlertController(text: """
计算方式：EV值 = 配套总额 × 3.2。例如，购买1000元配套，EV值为3200元。\n收益跟踪：每次获得收益后，EV值将逐渐减少，实时反映剩余收益潜力。\n复投提示：当EV值降至初始值的10%（如3200元降至320元）时，您需要复投新配套以继续获得收益。\n投资价值：EV值基于我们优化的算力收益模型，确保透明、高效的回报。
""", paragraphSpacing: 12).showIn(weakSelf)
        }
        
        buyComputingPowerAmountView.addTo(contentView)
        buyComputingPowerAmountView.totalAmountValueLabel.text = "0.00".formattedDecimal(decimals: 2)
        buyComputingPowerAmountView.layer.cornerRadius = 10
        buyComputingPowerAmountView.layer.masksToBounds = true
        buyComputingPowerAmountView.layer.borderWidth = 0.7
        buyComputingPowerAmountView.layer.borderColor = UIColorMake(0xD2D2D2).cgColor
//        buyComputingPowerAmountView.coinIconImageView.setImage(url: )
        buyComputingPowerAmountView.snp.makeConstraints { make in
            make.left.right.equalTo(buyPowerSelectCoinView)
            make.top.equalTo(computingPowerView.snp.bottom).offset(16)
        }
        
        buyButton.addTo(contentView)
        buyButton.isEnabled = false
        buyButton.addTarget(self, action: #selector(buyButtonTapped), for: .touchUpInside)
        buyButton.snp.makeConstraints { make in
            make.left.right.equalTo(buyPowerSelectCoinView)
            make.height.equalTo(AppStyle.size.buttonHeight.scaled)
            make.top.equalTo(buyComputingPowerAmountView.snp.bottom).offset(30)
        }
        
        lastView = buyButton
  
        updateContentSize()
        
        ComputingPowerService.loadBuyComputingPower(pool: model.pool, success: { infoModel in
            print("infoModel=\(infoModel)")
            self.infoModel = infoModel
        })
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
            PurchasePowerAlertController().showIn(self)
        })
    }
    
    @objc func priceInfoButtonTapped() {
        MessageAlertController(text: """
选择适合您的配套（$100 或 $2088）。\n使用“- / +”按钮调整购买数量，并查看购买总额与EV活力值。\n确认后点击“确认”完成熔铸算力。
""", paragraphSpacing: 12).showIn(self)
    }
    
    @objc func generalTypeViewMinusButton() {
        guard let model = generalTypeView.model else { return }
        reloadComputingPowerView(count: generalTypeView.count, model: model)
    }
    
    @objc func generalTypeViewPlusButton() {
        
        standardTypeView.count = 0
        
        guard let model = generalTypeView.model else { return }
        reloadComputingPowerView(count: generalTypeView.count, model: model)
    }
    
    @objc func standardTypeViewPlusButton() {
        generalTypeView.count = 0
        
        guard let model = standardTypeView.model else { return }
        reloadComputingPowerView(count: standardTypeView.count, model: model)
    }
    
    @objc func standardTypeViewMinusButton() {
        guard let model = standardTypeView.model else { return }
        reloadComputingPowerView(count: standardTypeView.count, model: model)
    }
    
    func reloadComputingPowerView(count: Int, model: BuyPowerOptionModel) {
        guard let infoModel = self.infoModel else { return }

        let maxCapValue: Float = Float(infoModel.maxCap) ?? 0
        let computingPowerValue = Float(count) * Float(model.invest) / 100.0
        let vitalityValue = maxCapValue * computingPowerValue * 100

        computingPowerView.computingPowerValue = computingPowerValue
        computingPowerView.vitalityValue = vitalityValue
   
        let coinAmount = Float(count) * Float(model.invest)

        buyComputingPowerAmountView.coinAmountLabel.text = String(coinAmount).formattedDecimal(decimals: 2)
        buyComputingPowerAmountView.totalAmountValueLabel.text = String(coinAmount).formattedDecimal(decimals: 2)
        
        changeBuyButtonEnableState()
    }
    
    private func buildPriceCodeView() {
                
        let priceTitleView = UIView().addTo(priceCodeView)
        priceTitleView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(40)
        }
        
        let priceTitleLabel = UILabel(text: "价格".localizedString, textColor: UIColor.white).addTo(priceTitleView)
        priceTitleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        
        let infoButton = UIButton(type: .system).addTo(priceTitleView)
        infoButton.addTarget(self, action: #selector(priceInfoButtonTapped), for: .touchUpInside)
        infoButton.setImage(UIImage(named: "more-info-icon"), for: .normal)
        infoButton.snp.makeConstraints { make in
            make.width.height.equalTo(20)
            make.left.equalTo(priceTitleLabel.snp.right).offset(8)
            make.centerY.equalTo(priceTitleLabel)
        }
        
        let priceStackView = UIStackView()
        priceStackView.axis = .vertical
        priceStackView.spacing = 16
        priceStackView.alignment = .center
        priceStackView.distribution = .equalSpacing
        priceCodeView.addSubview(priceStackView)
        priceStackView.snp.makeConstraints { make in
            make.left.right.equalTo(priceTitleView)
            make.top.equalTo(priceTitleView.snp.bottom)
        }

        generalTypeView.isHighlighted = false
        generalTypeView.minusButton.addTarget(self, action: #selector(generalTypeViewMinusButton), for: .touchUpInside)
        generalTypeView.plusButton.addTarget(self, action: #selector(generalTypeViewPlusButton), for: .touchUpInside)
        priceStackView.addArrangedSubview(generalTypeView)
        generalTypeView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(46)
        }

        standardTypeView.isHighlighted = false
        standardTypeView.minusButton.addTarget(self, action: #selector(standardTypeViewMinusButton), for: .touchUpInside)
        standardTypeView.plusButton.addTarget(self, action: #selector(standardTypeViewPlusButton), for: .touchUpInside)
        priceStackView.addArrangedSubview(standardTypeView)
        standardTypeView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(46)
        }
        
        codeTextField.titleLabel.text = "代码".localizedString
        codeTextField.titleLabel.textColor = .gray
        codeTextField.textField.attributedPlaceholder = NSAttributedString(string: "代码".localizedString, attributes: [NSAttributedString.Key.foregroundColor: UIColorMake(0x7F8292)])
        codeTextField.textField.keyboardType = .asciiCapable
        codeTextField.textFieldCornerRadius = 10
        priceCodeView.addSubview(codeTextField)
        codeTextField.textField.addTarget(self, action: #selector(textFieldDidChange(_ :)), for: .editingChanged)
        codeTextField.snp.makeConstraints { make in
            make.top.equalTo(standardTypeView.snp.bottom).offset(16)
            make.left.right.equalTo(priceTitleView)
            make.bottom.equalToSuperview()
        }
        
    }
    
    private func buildOutputIncomeView() -> UIView {
        
        let outputIncomeView = UIView()

        let outputIncomeLabel = UILabel(textColor: UIColorMake(0x0062FE)).addTo(outputIncomeView)
        outputIncomeLabel.attributedText = "产出收益".localizedString.titleMargin(3, font: UIFontMake(14))
        outputIncomeLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(2)
            make.centerY.equalToSuperview()
        }
        
        let iconsView = OverlapIconsView().addTo(outputIncomeView)
        iconsView.configure(imagesUrls: model.icons, size: 30, overlap: 0.3)
        iconsView.snp.makeConstraints { make in
            make.left.equalTo(outputIncomeLabel.snp.right).offset(20)
            make.centerY.equalToSuperview()
            make.height.equalTo(32)
        }
        
        let outputIncomeCoinLabel = UILabel(textColor: UIColor.white).addTo(outputIncomeView)
        outputIncomeCoinLabel.attributedText = "SCA + AIC".titleMargin(3, font: UIFontMake(14))
        outputIncomeCoinLabel.snp.makeConstraints { make in
            make.left.equalTo(iconsView.snp.right).offset(20)
            make.centerY.equalToSuperview()
        }
        return outputIncomeView
    }
    
    @objc func buyPowerSelectCoinViewTapped(_ tap: UITapGestureRecognizer) {
        guard let tapView = tap.view, let infoModel = self.infoModel else {
            return
        }
        
        let fromViewFrame = tapView.convert(tapView.bounds, to: UIApplication.shared.windows.first { $0.isKeyWindow })
        let selectCoinController = BuySelectCoinController(datas: infoModel.paymentOptions)
        selectCoinController.fromRect = CGRectMake(ceil(fromViewFrame.origin.x), ceil(fromViewFrame.origin.y), fromViewFrame.width, fromViewFrame.height)
        selectCoinController.onSelectCoin = {[weak self] model in
            self?.selectCoinChange(option: model)
        }
        present(selectCoinController, animated: false)
        
    }
    
    func selectCoinChange(option: BuyPowerPaymentOption) {
        
        printProperties(option)
        
        guard let infoModel = self.infoModel,
              let optionModels: [BuyPowerOptionModel] = infoModel.options[option.coin],
              let generalModel = optionModels.first,
              let standardModel = optionModels.last else {
            return
        }
        
        optionModels.forEach {
            printProperties($0)
        }
        
        buyComputingPowerAmountView.isShowCoin = true
        generalTypeView.model = generalModel
        standardTypeView.model = standardModel
        paymentOption = option
        buyPowerSelectCoinView.nameLabel.text = option.displayAmount
        
        buyComputingPowerAmountView.coinIconImageView.setImage(url: option.coinUrl)
        buyComputingPowerAmountView.coinNameLabel.text = option.coinName
        buyComputingPowerAmountView.coinAmountLabel.text = "0.00".formattedDecimal(decimals: 2)
        buyComputingPowerAmountView.totalAmountValueLabel.text = "0.00".formattedDecimal(decimals: 2)
        
        DispatchQueue.main.async {
            UIView.animate(withDuration: 0.25) {
                self.priceCodeView.alpha = 1
                self.computingPowerView.snp.remakeConstraints { make in
                    make.left.right.equalTo(self.buyPowerSelectCoinView)
                    make.top.equalTo(self.priceCodeView.snp.bottom).offset(10)
                }
                self.computingPowerView.superview?.layoutIfNeeded()
            } completion: { _ in
                self.updateContentSize()
                self.changeBuyButtonEnableState()
            }
        }
    }
    
    func changeBuyButtonEnableState() {
        
        var count: Int = 0
        if generalTypeView.count > 0 {
            count = generalTypeView.count
            
            if let option = self.paymentOption, option.isSelected, count > 0 {
                buyButton.isEnabled = true
            } else {
                buyButton.isEnabled = false
            }
            
        } else {
            count = standardTypeView.count
            if let option = self.paymentOption, let commitmentCode = codeTextField.textField.text, commitmentCode.count > 0, option.isSelected, count > 0 {
                buyButton.isEnabled = true
            } else {
                buyButton.isEnabled = false
            }
        }
    }
    
    struct PreviewBuyParameter {
        let invest100: Bool
        let payment: Float
        let coin: String
        let pool: String
        let commitmentCode: String
    }
    
    @objc func buyButtonTapped() {
        
        var buyPowerOptionModel: BuyPowerOptionModel?
        var count: Int?
        if generalTypeView.count > 0 {
            buyPowerOptionModel = generalTypeView.model
            count = generalTypeView.count
        } else {
            buyPowerOptionModel = standardTypeView.model
            count = standardTypeView.count
        }
        
        guard let option = self.paymentOption,
              let commitmentCode = codeTextField.textField.text,
              let buyCount = count,
                let optionModel = buyPowerOptionModel
        else {
            return
        }
        
//        ak2wrt2wn6
        let invest100: Bool = optionModel.invest == 100
        let payment = Float(buyCount) * Float(optionModel.invest)
        HUD.showLoadingInView(self.view)
        
        let paymentMix = "0"
        let pool = "aic"
        
        ComputingPowerService.previewBuyComputingPower(coin: option.coin, pool: pool, commitmentCode: commitmentCode, invest100: invest100, payment: payment, paymentMix: paymentMix, success: { previewBuyComputingPowerModel in
            HUD.hideHUD(for: self.view)
            
            let buyPreViewController = BuyPreViewController(model: previewBuyComputingPowerModel)
            buyPreViewController.onCommit = { password in
                
                HUD.showLoadingInView(self.view)
                ComputingPowerService.buyComputingPower(coin: option.coin, pool: pool, commitmentCode: commitmentCode, password: password, invest100: invest100, payment: payment, paymentMix: paymentMix, success: { message in
                    HUD.hideHUD(for: self.view)

                    NotificationCenter.default.post(name: NotificationName.buyPowerSucceed, object: nil)
                    
                    let buySucceedController = BuySucceedController(messsage: message)
                    buySucceedController.onDismiss = {
                        
                        let powerDetailController = PowerDetailController(pool: pool, poolName: self.model.title, poolIconUrl: self.model.poolIcon)
                        self.navigationController?.pushViewController(powerDetailController, animated: true)
                        self.navigationController?.viewControllers = self.removeNavChildViewControllers([
                            "BuyPowerController",
                            "PurchasePowerListController",
                        ])
                        
                    }
                    buySucceedController.showIn(self)
                }) { error in
                    HUD.showErrorMessage(error)
                }
            }
            buyPreViewController.showIn(self)
        }) { error in
            HUD.showErrorMessage(error)
        }
        
//  
//"step":"preview",
//            "wallet":"usca",
//            "wallet_mix":"",
//            "duration":"",
//            "commitment_code":"i9aej8y0mv",
//            "payment":100,
//            "payment_mix":"0",
//            "invest_100":1,
//            "invest_2088":0,
        
        
    }
    
    @objc func textFieldDidChange(_ sender: UITextField) {
        changeBuyButtonEnableState()
    }
    
    private func updateContentSize() {
        
        contentView.setNeedsLayout()
        contentView.layoutIfNeeded()
        
        let contentSize = CGSizeMake(view.width, lastView.maxY + 10 + tabBarSafeBottomMargin)
        scrollView.contentSize = contentSize
        contentView.snp.remakeConstraints { make in
            make.edges.equalToSuperview()
            make.size.equalTo(contentSize)
        }
    }
 

}


 
